<script setup>
import CommonModal from "../../components/modal/CommonModal.vue";
import { ref, onMounted, watch, onUnmounted } from "vue";
import { salesFinacePage } from "@/api/user";
import { getBankInfo, bindBankCard, getSmsCode } from "@/api/user";
import { useUser } from "@/store/useUser.js";
import { storeToRefs } from "pinia";
import { ElMessage } from 'element-plus';

const userStore = useUser();
const { userInfo } = storeToRefs(userStore);

// 绑定银行卡
const formData = ref({
  id: null, // 银行卡ID，用于更新时传递
  sysUserId: null,
  payeeName: '', // 收款人姓名
  identityCard: '', // 收款人身份证
  bankName: '', // 所属银行名称
  bankAccount: '', // 银行卡号
  smsCode: '' // 短信验证码
});

const bindCardModalShow = ref(false);
const submitLoading = ref(false);
const smsLoading = ref(false);
const countdown = ref(0);
const countdownTimer = ref(null);
const formRef = ref(null);

// 表单验证规则
const formRules = {
  payeeName: [
    { required: true, message: '请输入收款人姓名', trigger: 'blur' }
  ],
  identityCard: [
    { required: true, message: '请输入收款人身份证', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  bankName: [
    { required: true, message: '请输入所属银行', trigger: 'blur' }
  ],
  bankAccount: [
    { required: true, message: '请输入银行卡号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '请输入正确的银行卡号', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ]
};

// 获取收入信息
const incomeInfo = ref({
  pendAmount: 0,
  postAmount: 0,
  disbursedAmount: 0,
  orderList: [],
  total: 0,
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 添加当前选中的标签状态
const currentStatus = ref(1); // 默认为待发放

// 添加加载状态
const loading = ref(false);

const fetchIncomeInfo = async () => {
  loading.value = true;
  try {
    const response = await salesFinacePage({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      status: currentStatus.value,
    });
    incomeInfo.value = response.data;
  } catch (error) {
    console.error("获取收入信息失败", error);
  } finally {
    loading.value = false;
  }
};

// 获取银行卡信息
const fetchBankInfo = async () => {
  try {
    const response = await getBankInfo();
    if (response.data && response.data.id) {
      // 如果有银行卡信息，回填表单
      formData.value = {
        id: response.data.id,
        sysUserId: response.data.sysUserId,
        payeeName: response.data.payeeName || '',
        identityCard: response.data.identityCard || '',
        bankName: response.data.bankName || '',
        bankAccount: response.data.bankAccount || '',
        smsCode: ''
      };
    }
  } catch (error) {
    console.error("获取银行卡信息失败", error);
  }
};

// 提交绑定银行卡
const bindCardSubmit = async () => {
  // 表单验证
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
  } catch (error) {
    console.log('表单验证失败', error);
    return;
  }

  submitLoading.value = true;
  try {
    const submitData = {
      ...formData.value,
      sysUserId: userInfo.value?.userId || formData.value.sysUserId
    };
    
    const response = await bindBankCard(submitData);
    if (response.data) {
      ElMessage.success(formData.value.id ? '银行卡信息更新成功' : '银行卡绑定成功');
      closeBindCardModal();
      // 重新获取银行卡信息
      await fetchBankInfo();
    }
  } catch (error) {
    console.error("绑定银行卡失败", error);
  } finally {
    submitLoading.value = false;
  }
};

// 获取短信验证码
const getSmsCodeHandler = async () => {
  if (!userInfo.value?.phonenumber) {
    ElMessage.warning('请先绑定手机号');
    return;
  }
  
  if (countdown.value > 0) {
    return;
  }

  smsLoading.value = true;
  try {
    await getSmsCode({
      mobile: userInfo.value.phonenumber,
      type: 5 // 根据实际需要调整验证码类型
    });
    ElMessage.success('验证码已发送');
    
    // 开始倒计时
    countdown.value = 60;
    countdownTimer.value = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer.value);
        countdownTimer.value = null;
      }
    }, 1000);
  } catch (error) {
    console.error("获取验证码失败", error);
    ElMessage.error('获取验证码失败，请重试');
  } finally {
    smsLoading.value = false;
  }
};

// 打开绑定银行卡弹窗
const openBindCardModal = () => {
  bindCardModalShow.value = true;
  // 每次打开弹窗时重新获取银行卡信息
  fetchBankInfo();
};

// 关闭弹窗时清理倒计时
const closeBindCardModal = () => {
  bindCardModalShow.value = false;
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
    countdownTimer.value = null;
    countdown.value = 0;
  }
  // 重置表单验证状态
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

onMounted(() => {
  fetchIncomeInfo();
  fetchBankInfo(); // 页面加载时获取银行卡信息
});

watch([currentPage, pageSize], () => {
  fetchIncomeInfo();
});

// 格式化金额
const formatAmount = (amount) => {
  return amount.toFixed(2);
};

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 添加处理标签点击的函数
const handleTabClick = (status) => {
  currentStatus.value = status;
  currentPage.value = 1; // 重置页码
  fetchIncomeInfo();
};

// 监听标签状态变化
watch(currentStatus, () => {
  fetchIncomeInfo();
});

// 组件销毁时清理定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
    countdownTimer.value = null;
  }
});
</script>

<template>
  <div>
    <div class="fund-list">
      <img class="bg-icon" src="@/assets/fund-list-bg.png" alt="" />
      <div class="fund-item">
        <h5>待发放</h5>
        <p>每月10号，平台自动将上个月已完结的收入转至你绑定的银行账户</p>
        <div>
          <span>¥</span>
          <span>{{ formatAmount(incomeInfo.pendAmount) }}</span>
        </div>
      </div>
      <span class="line"></span>
      <div class="fund-item">
        <h5>待入账</h5>
        <p>当前履约中、尚未完成交付验收的订单收入，已冻结到平台，待发放</p>
        <div>
          <span>¥</span>
          <span>{{ formatAmount(incomeInfo.postAmount) }}</span>
        </div>
      </div>
      <span class="line"></span>
      <div class="fund-item">
        <h5>已发放</h5>
        <p>你在技能猴子服务平台累计已结算的服务费收入总合</p>
        <div>
          <span>¥</span>
          <span>{{ formatAmount(incomeInfo.disbursedAmount) }}</span>
        </div>
      </div>
    </div>
    <div class="fund-goods">
      <div class="tabs-box">
        <p class="tabs">
          <span
            :class="{ active: currentStatus === 1 }"
            @click="handleTabClick(1)"
            >待发放</span
          >
          <span
            :class="{ active: currentStatus === 2 }"
            @click="handleTabClick(2)"
            >待入账</span
          >
          <span
            :class="{ active: currentStatus === 3 }"
            @click="handleTabClick(3)"
            >已发放</span
          >
        </p>
        <span class="bingCard" @click="openBindCardModal"
          >绑定/更换银行卡</span
        >
      </div>
      <div class="fund-goods-list" v-loading="loading">
        <template
          v-if="incomeInfo.orderList && incomeInfo.orderList.length > 0"
        >
          <div v-for="item in incomeInfo.orderList" :key="item.id" class="item">
            <img class="goods-img" :src="item.coverPic" :alt="item.goodsName" />
            <div class="info">
              <p class="goods-name">{{ item.goodsName }}</p>
              <p class="order-info">
                <span class="date">{{ formatDate(item.orderTime) }}</span>
                <span class="end-amount"
                  >¥{{ formatAmount(item.actualAmount) }}</span
                >
              </p>
              <div class="buyer-info">
                <p class="name-head">
                  买家：<img :src="item.buyerProfile" alt="" />{{
                    item.nickName
                  }}
                </p>
                <p class="amount">
                  订单总价 ¥{{ formatAmount(item.totalAmount) }} - 平台费（{{
                    item.commissionRate * 100
                  }}%） ¥{{ formatAmount(item.commission) }}
                </p>
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <el-empty description="暂无数据" />
        </template>
      </div>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          background
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="incomeInfo.total"
          layout="total, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <CommonModal
      title="绑定银行卡"
      v-if="bindCardModalShow"
      :show="bindCardModalShow"
      :loading="submitLoading"
      @close="closeBindCardModal"
      @confirm="bindCardSubmit"
    >
      <template #content>
        <el-form
          class="bind-card-form"
          :model="formData"
          :rules="formRules"
          ref="formRef"
          label-position="top"
          style="padding-top: 10px"
        >
          <el-row gutter="20">
            <el-col :span="12">
              <el-form-item label="收款人姓名" prop="payeeName">
                <el-input
                  v-model="formData.payeeName"
                  placeholder="请输入收款人姓名"
                  style="height: 40px"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收款人身份证" prop="identityCard">
                <el-input
                  v-model="formData.identityCard"
                  placeholder="请输入收款人身份证"
                  style="height: 40px"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row gutter="20">
            <el-col :span="12">
              <el-form-item label="所属银行" prop="bankName">
                <el-input
                  v-model="formData.bankName"
                  placeholder="请输入所属银行"
                  style="height: 40px"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行卡号" prop="bankAccount">
                <el-input
                  v-model="formData.bankAccount"
                  placeholder="请输入银行卡号"
                  style="height: 40px"
                  maxlength="19"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="短信验证码" prop="smsCode">
                <el-input
                  v-model="formData.smsCode"
                  placeholder="请输入短信验证码"
                  style="height: 40px"
                  maxlength="6"
                >
                  <template #append>
                    <el-button 
                      type="primary" 
                      plain 
                      :loading="smsLoading"
                      :disabled="countdown > 0"
                      @click="getSmsCodeHandler"
                    >
                      {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </CommonModal>
  </div>
</template>

<style scoped lang="scss">
.tabs-box {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #ccc;
  padding-bottom: 12px;
  margin-bottom: 24px;
  .tabs {
    display: flex;
    align-items: center;
    span {
      margin-right: 40px;
      cursor: pointer;
      &.active {
        color: #1dbf73;
        font-weight: bold;
        position: relative;
        &:after {
          content: "";
          display: block;
          width: 100%;
          height: 2px;
          background: #1dbf73;
          position: absolute;
          bottom: -12px;
          left: 0;
        }
      }
    }
  }
  a {
    width: 108px;
    height: 36px;
    background: #1dbf73;
    border-radius: 8px 8px 8px 8px;
    text-align: center;
    line-height: 36px;
    color: #fff;
    text-decoration: none;
  }
}
.fund-list {
  background: linear-gradient(135deg, #1b1d24 0%, #33353c 100%);
  border-radius: 24px 24px 24px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  padding: 36px 190px;
  color: rgba(245, 202, 158, 1);
  .bg-icon {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 190px;
    height: 170px;
  }
  .line {
    width: 1px;
    height: 96px;
    background: rgba(245, 200, 159, 0.24);
    margin: 0 10px;
  }
  .fund-item {
    position: relative;
    z-index: 1;
  }
  h5 {
    font-size: 16px;
    line-height: 19px;
    margin-bottom: 6px;
  }
  p {
    color: rgba(255, 235, 207, 0.6);
    max-width: 250px;
    margin-bottom: 18px;
  }
  div {
    span {
      font-size: 36px;
    }
    span:nth-child(1) {
      font-size: 20px;
    }
  }
}
.fund-goods {
  flex: 1;
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  margin-top: 16px;
  padding: 20px;
  box-sizing: border-box;
}
.fund-goods-list {
  .item {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    padding: 16px 0;
  }
  .goods-img {
    width: 200px;
    height: 129px;
    margin-right: 16px;
    object-fit: cover;
    border-radius: 8px;
    background: #ddd;
  }
  .info {
    flex: 1;
  }
  .goods-name {
    font-size: 18px;
    color: #191e28;
    line-height: 28px;
    font-weight: bold;
    // 超出两行显示省略号
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .order-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .date {
      color: rgba(25, 30, 40, 0.72);
      font-size: 12px;
    }
    .end-amount {
      font-size: 32px;
      font-weight: 800;
      color: #191e28;
    }
  }
  .buyer-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .name-head {
      display: flex;
      align-items: center;
      color: #191e28;
      img {
        width: 20px;
        height: 20px;
        margin-right: 5px;
      }
    }
    .amount {
      font-size: 12px;
      color: rgba(25, 30, 40, 0.36);
    }
  }
}
.fund-list {
  background: linear-gradient(135deg, #1b1d24 0%, #33353c 100%);
  border-radius: 24px 24px 24px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  padding: 36px 190px;
  color: rgba(245, 202, 158, 1);
  .bg-icon {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 190px;
    height: 170px;
  }
  .line {
    width: 1px;
    height: 96px;
    background: rgba(245, 200, 159, 0.24);
  }
  .fund-item {
    position: relative;
    z-index: 1;
  }
  h5 {
    font-size: 16px;
    line-height: 19px;
    margin-bottom: 6px;
  }
  p {
    color: rgba(255, 235, 207, 0.6);
    max-width: 250px;
    margin-bottom: 18px;
  }
  div {
    span {
      font-size: 36px;
    }
    span:nth-child(1) {
      font-size: 20px;
    }
  }
}
.fund-goods {
  flex: 1;
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  margin-top: 16px;
  padding: 20px;
  box-sizing: border-box;
  .bingCard {
    cursor: pointer;
    transition: all 0.2s ease;
    &:hover {
      font-weight: bold;
    }
  }
}
.fund-goods-list {
  .item {
    display: flex;
    align-items: center;
  }
  .goods-img {
    width: 200px;
    height: 129px;
    margin-right: 16px;
  }
  .goods-name {
    font-size: 18px;
    color: #191e28;
    line-height: 28px;
    font-weight: bold;
    // 超出两行显示省略号
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .order-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .date {
      color: rgba(25, 30, 40, 0.72);
      font-size: 12px;
    }
    .end-amount {
      font-size: 32px;
      font-weight: 800;
      color: #191e28;
    }
  }
  .buyer-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .name-head {
      display: flex;
      align-items: center;
      color: #191e28;
      img {
        width: 20px;
        height: 20px;
        margin-right: 5px;
      }
    }
    .amount {
      font-size: 12px;
      color: rgba(25, 30, 40, 0.36);
    }
  }
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 可以添加一些加载状态的自定义样式 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
}

:deep(.el-loading-spinner .circular) {
  width: 42px;
  height: 42px;
  animation: loading-rotate 2s linear infinite;
}
</style>

<style>
.bind-card-form .el-form-item__label {
  font-weight: bold;
  color: #333;
}
.bind-card-form .el-input__wrapper {
  border-radius: 6px 6px 6px 6px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  box-shadow: none;
}
.bind-card-form .el-input-group__append,
.el-input-group__prepend {
  background: none;
  box-shadow: none;
  border: 1px solid rgba(25, 30, 40, 0.08);
  box-sizing: border-box;
  color: #1dbf73;
}
</style>
